package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.vo.BasePageData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.DataBean;
import com.cskaoyan.service.UserService;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.utils.BaseRespVoUtil;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 *  小程序登录
 */
@RestController
public class WxAuthLoginController {

    @Autowired
    UserService userService;

    @RequestMapping("wx/auth/login")
    public BaseRespVo userLogin(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        Subject subject = SecurityUtils.getSubject();
        // 参数判断
        if(username == null && username.equals("")){
            return BaseRespVo.fail("用户名输入不能为空");
        }
        if(password == null && password.equals("")){
            return BaseRespVo.fail("密码不能为空");
        }
        MallToken mallToken = new MallToken(username, password, "wx");
        // 执行登录
        subject.login(mallToken);
        // 是否认证成功
        boolean authenticated = subject.isAuthenticated();


        if(!authenticated){
            return BaseRespVo.fail("用户或密码错误，请重试");
        }

        DataBean dataBean = new DataBean();
        DataBean.UserInfoBean userInfo = new DataBean.UserInfoBean();
        userInfo.setAvatar("https://s3.ifanr.com/wp-content/uploads/2018/04/avengers-infinity-war-d23-artwork-8k-dl-2048x1152.jpg!720");
        userInfo.setNickName(username);
        dataBean.setUserInfo(userInfo);
        dataBean.setToken((String) subject.getSession().getId());
        subject.getSession().setAttribute("username",username);
        System.out.println("login请求的sessionId：" + subject.getSession().getId());
        return BaseRespVo.ok(dataBean);
    }

    /**
     *  用户退出
     *
     */
    @RequestMapping("wx/auth/logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        if(subject != null){
            subject.logout();
        }
        return BaseRespVo.ok();
    }



}
